<template>
  <div>
    <div class="independentPointSwitch" v-if="point">
      <span>
        独立提货点
        <span class="tip"
          >开启后系统将团长部分功能拆分至提货点；原先订单数据也会受到影响，请谨慎操作</span
        >
      </span>
      <el-switch
        class="switch"
        v-model="isIndependentPoint"
        :active-value="1"
        :inactive-value="0"
        @change="isIndependentPointChange"
      ></el-switch>
    </div>
    <m-card
      class="form"
      hide-text="展开搜索条件"
      show-text="收起搜索条件"
      :needToggle="true"
    >
      <el-form ref="form" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="提货点名称">
              <el-input
                v-model="form.name"
                placeholder="请输入提货点名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="ID" style="font-size: 14px">
              <el-input v-model="form.id" placeholder="请输入ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">
              <el-input
                v-model="form.phone"
                placeholder="请输入电话"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区">
              <el-input
                v-model="form.location"
                placeholder="请输入地区"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option label="全部" value="2"></el-option>
                <el-option label="自定义提货点" value="0"></el-option>
                <el-option label="菜鸟驿站" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="searchClick">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </m-card>
    <el-tabs v-model="currentTab" type="card" style="margin-top: 20px">
      <el-tab-pane label="提货点列表" name="PointList"></el-tab-pane>
      <el-tab-pane label="待审核" name="PointCheck"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="PointRefuse"></el-tab-pane>
      <el-tab-pane label="禁用中" name="PointDisable"></el-tab-pane>
    </el-tabs>
    <div class="pickpage" v-if="isIndependentPoint == 1">
      <div class="pickpage__head" style="margin-bottom: 20px">
        <el-button
          type="primary"
          @click="getShipperPointMoneySets"
          v-if="currentTab === 'PointList' || currentTab === 'PointDisable'"
          >佣金设置</el-button
        >
        <el-button :disabled="deletLinesStatus" @click="deletePoints(undefined)"
          >批量删除</el-button
        >
      </div>

      <AddrTabel
        v-if="
          isIndependentPoint == 1 &&
            (currentTab === 'PointList' || currentTab === 'PointDisable')
        "
        ref="addrTabel"
        :tabelList="tabelList"
        :deletLinesStatus.sync="deletLinesStatus"
        @deletePoints="deletePoints"
        @setPointStatus="setPointStatus"
        @refreshTabelData="getTabelList"
      ></AddrTabel>

      <AddrLessTable
        v-if="
          isIndependentPoint == 1 &&
            (currentTab === 'PointCheck' || currentTab === 'PointRefuse')
        "
        ref="addrTabel"
        :tabelList="tabelList"
        :deletLinesStatus.sync="deletLinesStatus"
        :currentTab="currentTab"
        @deletePoints="deletePoints"
        @refreshTabelData="getTabelList"
      ></AddrLessTable>

      <PageManage
        v-if="isIndependentPoint == 1"
        :pageSize="form.size"
        :pageNum="form.current"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></PageManage>

      <CommissionSetUp
        v-if="isIndependentPoint == 1"
        v-model="commissionSetting"
        :commissionDialog.sync="commissionDialog"
        @save="onSettingSave"
      />

      <!-- <CommissionSetUp :commissionDialog.sync="commissionDialog"
                      :setUp="setUp"
                      @emitSetUpData="emitSetUpData">
      </CommissionSetUp>-->
    </div>
    <div class="notIndependentPoint" v-if="isIndependentPoint == 0">
      您尚未开启独立提货点
    </div>
    <el-dialog :visible.sync="deleteType" width="400px" :before-close="cancel">
      <div class="center">
        <ScanQrCode
          :redirectUrl="redirectUrl"
          scenes="AccountShopInfoCheck"
          :shopInfoId="shopInfoId"
        />
        <div style="width:100%; margin-top: 20px" class="center">
          请管理员扫码
        </div>
      </div>
    </el-dialog>
    <UpMealTP v-if="!point" />
  </div>
</template>

<script lang="ts">
import { Vue, Component, PropSync, Ref, Watch } from "vue-property-decorator";
import AddrTabel from "./AddrTabel.vue";
import AddrLessTable from "./AddrLessTable.vue";
import CommissionSetUp from "./CommissionSetUp.vue";
import PageManage from "@/components/PageManage.vue";
import UpMealTP from "../upMeal/UpMealTP.vue";
import {
  setShipperPointMoney,
  getShipperPointList,
  setShipperPoints,
  setPointStatusSingle,
} from "@/api/rection/index";
import {
  getPotintSetting,
  setPotintSetting,
  getShopFunction,
} from "@/api/finance";
import { verifyStateResult } from "@/api/sign";
import { getIsMergePoint, setIsMergePoint } from "@/api/group/group";
import ScanQrCode from "@/components/ScanQrCode.vue";
import store from "@/store";

@Component({
  components: {
    AddrTabel,
    CommissionSetUp,
    PageManage,
    UpMealTP,
    AddrLessTable,
    ScanQrCode,
  },
})
export default class PickUpPoint extends Vue {
  /** 顶部switch状态 */
  @PropSync("state", { type: Boolean, default: false })
  syncState: boolean;

  isIndependentPoint: number | string = "";

  /** 佣金设置弹框 */
  commissionDialog = false;

  /** 卡片点击选择 */
  currentTab = "PointList" as any;

  @Watch("currentTab")
  changeCurrentTab() {
    this.tabelList = [];
    this.getStatus();
    this.getTabelList();
  }

  /** 关闭提货点弹窗 */
  deleteType = false;

  /** 重定向地址 */
  redirectUrl = "";

  shopInfoId = this.$store.state.user.userInfo.shopInfoVo.platformShopId;

  /** 分页参数 */
  pageSize = 20;

  pageIndex = 1;

  total = 0;

  /** 批量生产删除按钮状态 */
  deletLinesStatus = true;

  form = {
    type: "2",
    id: "",
    phone: "",
    name: "",
    location: "",
    //  0-已审核 1-禁用中 2-待审核 3-已拒绝
    pointStatus: 0,
    current: 1,
    size: 20,
  };

  /** 搜索参数 */
  searchData = {
    /** 租户id */
    tenantId: "",
    /** 城市合伙人id  */
    userId: "",
    pageIndex: 1,
    pageSize: 20,
    type: -1,
    inputText: -1,
    text: "",
  };

  /** 佣金设置默认值 */
  setUp = {
    /** 租户id  */
    tenantId: "",
    /** 城市合伙人id  */
    userId: "",
    /** 主键id，初次不传，后续根据get接口返回的id */
    id: "",
    /** 起提金额，单位元 */
    pointMoney: 0,
    /** 类型：0=按照订单数，1=月结 */
    type: 0,
    /** 当type=1，启用 */
    monthPay: 0,
    /** 当type=0启用 */
    orderNum: [
      {
        num: [0, 100],
        money: 0.3,
      },
    ],
  };

  /** 列表数据 */
  tabelList = [];

  /** 佣金设置 */
  commissionSetting = [];

  code = "";

  /** 该账号是否有提货点功能 */
  point = true;

  @Ref("addrTabel")
  refAddrTabel: any;

  getStatus() {
    switch (this.currentTab) {
      case "PointList":
        this.form.pointStatus = 0;
        break;
      case "PointCheck":
        this.form.pointStatus = 2;
        break;
      case "PointRefuse":
        this.form.pointStatus = 3;
        break;
      case "PointDisable":
        this.form.pointStatus = 1;
        break;
    }
  }

  created() {
    this.getPotintSetting();
    this.getIsMergePoint();
  }

  /**
   * 根据条件搜索
   */
  searchClick() {
    this.getTabelList();
  }

  // 获取是否开启提货点合并
  async getIsMergePoint() {
    const result = await getIsMergePoint();
    const data = result.data || 0;
    // 0:未开启 1：已开启
    this.isIndependentPoint = data;
  }

  cancel() {
    this.deleteType = false;
  }

  async isIndependentPointChange(data) {
    this.isIndependentPoint = data == 0 ? 1 : 0;
    this.deleteType = true;
    this.redirectUrl = `/distribution?data=${data}`;
  }

  /** 获取提货点佣金设置 */
  getPotintSetting() {
    getPotintSetting()
      .then(res => {
        this.commissionSetting = res.data;
      })
      .catch(err => {
        this.$message.warning(err);
      });
  }

  /** 保存提货点佣金设置 */
  onSettingSave(form) {
    setPotintSetting(form)
      .then(() => {
        this.getPotintSetting();
      })
      .catch(err => {
        this.$message.warning(err);
      });
  }

  /**
   * 获取佣金设置
   */
  getShipperPointMoneySets() {
    this.commissionDialog = true;
  }

  /**
   * 描述 更新佣金设置对象
   */
  emitSetUpData(data) {
    const param = {
      ...this.setUp,
      ...data,
    };
    setShipperPointMoney(param)
      .then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.commissionDialog = false;
        }
      })
      .catch(err => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 重置表格数据
   */
  reasetTabelData() {
    this.form.current = 1;
    this.getTabelList();
  }

  /**
   * @method handleSizeChange
   * @description 每页 条
   */
  handleSizeChange(val) {
    this.form.size = val;
    this.reasetTabelData();
  }

  /**
   * @method handleCurrentChange
   * @description 当前页
   */
  handleCurrentChange(val) {
    this.form.current = val;
    this.getTabelList();
  }

  /**
   * 重置搜索
   */
  resetSearch() {
    this.form.current = 1;
    this.getTabelList();
  }

  /**
   * 获取列表数据
   */
  getTabelList() {
    const param = JSON.parse(JSON.stringify(this.form));
    param.type = this.form.type === "2" ? "" : this.form.type;
    getShipperPointList(param)
      .then(res => {
        if (res.code === 200) {
          if (res.data.length) {
            this.tabelList = res.data;
            this.total = Number((res as any).totalCount);
          } else if (!res.data.length && this.form.current > 1) {
            this.form.current--;
            this.getTabelList();
            this.total = 0;
          } else {
            this.tabelList = [];
            this.total = 0;
          }
        }
      })
      .catch(err => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 删除提货点
   */
  deletePoints(data) {
    if (!data) {
      data = this.refAddrTabel.deleteIds;
    }
    if (!data.length) {
      this.$message.error("请选择需要删除项");
      return false;
    }
    this.$confirm("删除后选中的提货点信息无法恢复，确认删除？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      const param = {
        lists: data,
      };
      setShipperPoints(param)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getTabelList();
          }
        })
        .catch(err => {
          this.$message.error(err || "网络异常，请稍后重试");
        });
    });
  }

  /**
   * 提货点禁用
   */
  setPointStatus(data) {
    let pointType = 1;
    pointType = this.currentTab === "PointDisable" ? 0 : 1;
    this.$confirm(
      `确认${this.currentTab === "PointDisable" ? "启用" : "禁用"}此提货点`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(() => {
      setPointStatusSingle(`?pointStatus=${pointType}&pointId=${data}`)
        .then(() => {
          this.$message.success("设置成功");
          this.getTabelList();
        })
        .catch(err => {
          this.$message.error(err || "网络异常，请稍后重试");
        });
    });
  }

  async getFuction() {
    const params = {
      tenantId: store.state.user.userInfo.shopInfoVo.tenantId,
      shopId: store.state.user.userInfo.shopInfoVo.shopId,
    };
    getShopFunction(params)
      .then(res => {
        this.point = res.data.point;
      })
      .catch(err => {
        this.$message.error(err);
      });
  }

  getUrlParam(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
    const r = window.location.search.substr(1).match(reg); // 匹配目标参数
    if (r != null) {
      return unescape(r[2]);
    }
    return null; // 返回参数值
  }

  async mounted() {
    try {
      const data = this.getUrlParam("data");
      this.code = this.getUrlParam("code");
      const shopInfoId = this.getUrlParam("shopInfoId");
      const userInfo = this.$store.state.user.userInfo;
      const isValid =
        userInfo && userInfo.shopInfoVo && userInfo.shopInfoVo.platformShopId;
      if (isValid && userInfo.shopInfoVo.platformShopId === shopInfoId) {
        history.pushState(
          {},
          null,
          `${location.href.replace(/&?code=.*&?$/, "")}`,
        );
        const response = await verifyStateResult({
          code: this.code,
        });
        const { code } = response;
        if (code === 200) {
          try {
            const result = await setIsMergePoint(data);
            if (result.code == 200) {
              this.isIndependentPoint = Number(data);
            } else {
              throw new Error(result.msg);
            }
          } catch (error) {
            let errorMsg = error;
            if (!errorMsg) {
              const type = data === "0" ? "开启" : "关闭";
              errorMsg = `${type}独立提货点失败，请稍后重试`;
            }
            this.isIndependentPoint = data == "0" ? 1 : 0;
            this.$message.error(errorMsg);
          }
        }
      }
    } catch (e) {
      this.$message({
        message: e,
        type: "warning",
      });
    }

    if (this.$route.query.reback) {
      this.currentTab = this.$route.query.reback;
      this.getStatus();
    }
    this.getFuction();
    this.getTabelList();
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/logistics/pickPoint.scss";
.notIndependentPoint {
  text-align: center;
  line-height: 40px;
  font-size: 20px;
  color: #888;
}
.independentPointSwitch {
  margin-bottom: 10px;
  border-radius: 5px;
  background: #f6f8fa;
  padding: 15px;
  .tip {
    color: #aaa;
  }
  .switch {
    float: right;
  }
}

.center {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

/deep/ .el-form-item__label {
  font-size: 13px;
}
</style>
